﻿using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;

namespace DevHub.WindowsApp.Pages.Encode;

public partial class HtmlEncodeView : UserControl
{
    public HtmlEncodeView()
    {
        InitializeComponent();
    }

    private void CopyDecryptClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(DecryptBox.Text)) return;
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(DecryptBox.Text);
    }

    private void ClearDecryptClick(object? sender, RoutedEventArgs e)
    {
        DecryptBox.Text = "";
    }

    private void CopyEncryptClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(EncryptBox.Text)) return;
        var top = TopLevel.GetTopLevel(this);
        top?.Clipboard?.SetTextAsync(EncryptBox.Text);
    }

    private void ClearEncryptClick(object? sender, RoutedEventArgs e)
    {
        EncryptBox.Text = "";
    }

    private void ToggleIsCheckedChanged(object? sender, RoutedEventArgs e)
    {
        (EncryptBox.Text, DecryptBox.Text) = (DecryptBox.Text, EncryptBox.Text);
    }

    private async void OpenFileClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;
        var resultList = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions());
        if (resultList.Count == 0) return;
        var reader = new StreamReader(await resultList[0].OpenReadAsync());
        EncryptBox.Text = await reader.ReadToEndAsync();
    }

    private void EncryptTextChanged(object? sender, TextChangedEventArgs e)
    {
        if (Switch.IsChecked!.Value)
        {
            DecryptBox.Text = EncryptBox.Text?.Replace("&lt;", "<")
                .Replace("&gt;", ">")
                .Replace("&quot;", "\"");
        }
        else
        {
            DecryptBox.Text = EncryptBox.Text?.Replace("<", "&lt;")
                .Replace(">", "&gt;")
                .Replace("\"", "&quot;");
        }
    }
}